package com.lemeshko.xmlTest;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.adapters.XmlAdapter;

public class ObjectBinder {

	public static void marchalObjectsIntoFile(Object object, String url)
			throws JAXBException, IOException {

		JAXBContext contex = JAXBContext.newInstance(object.getClass());
		Marshaller marshaller = contex.createMarshaller();
		marshaller.marshal(object, new File(url));
	}

	public static String marchalObjectsIntoString(Object object)
			throws JAXBException {

		Writer writer = new StringWriter();

		JAXBContext contex = JAXBContext.newInstance(object.getClass());
		Marshaller marshaller = contex.createMarshaller();
		marshaller.marshal(object, writer);

		return writer.toString();
	}

	public static Object unmarshallFromResourceClassPath(String name,
			Class<?> clazz) throws JAXBException {

		InputStream is = clazz.getClassLoader().getResourceAsStream(name);
		JAXBContext context = JAXBContext.newInstance(clazz);
		Unmarshaller unmarshaller = context.createUnmarshaller();
		return unmarshaller.unmarshal(is);
	}

	public static Object unmarshalFromFile(String url, Class<?> clazz)
			throws JAXBException {

		JAXBContext context = JAXBContext.newInstance(clazz);
		Unmarshaller unmarchaller = context.createUnmarshaller();
		return unmarchaller.unmarshal(new File(url));

	}

	public static Object unmarshallFormString(String res, Class<?> clazz)
			throws JAXBException {

		StringReader reader = new StringReader(res);

		JAXBContext context = JAXBContext.newInstance(clazz);
		Unmarshaller unmarchaller = context.createUnmarshaller();
		return unmarchaller.unmarshal(reader);
	}

	public static class JaxbDateSerializer extends XmlAdapter<String, Date> {

		private final SimpleDateFormat dateFormat = new SimpleDateFormat(
				"yyyy-MM-dd");

		@Override
		public String marshal(Date date) throws Exception {
			return dateFormat.format(date);
		}

		@Override
		public Date unmarshal(String date) throws Exception {
			return dateFormat.parse(date);
		}
	}

}
